<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="录入时间" prop="outTime">
          <el-date-picker
              v-model="queryParams.recordTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="!w-[240px]"
          />
        </el-form-item>
        <el-form-item label="审核时间" prop="outTime">
          <el-date-picker
              v-model="queryParams.auditTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="!w-[240px]"
          />
        </el-form-item>
        <el-form-item label="旅行社名称" prop="deptId">
          <el-tree-select
              v-model="queryParams.deptId"
              placeholder="全部"
              :data="deptOptions"
              filterable
              clearable
              check-strictly
              :render-after-expand="false"
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryId">
          <el-tree-select
              v-model="queryParams.categoryId"
              placeholder="全部"
              :data="categoryOptions"
              filterable
              clearable
              check-strictly
              :render-after-expand="false"
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="录入人" prop="recordUserName">
          <el-input
              v-model="queryParams.recordUserName"
              placeholder="录入人"
              clearable
              @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="审核人" prop="auditUserName">
          <el-input
              v-model="queryParams.auditUserName"
              placeholder="审核人"
              clearable
              @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="审核结果" prop="auditResult">
          <el-select
              v-model="queryParams.auditResult"
              placeholder="全部"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery()"
          >
            <el-option label="待审核" value="1"/>
            <el-option label="审核通过" value="2"/>
            <el-option label="审核拒绝" value="3"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search/>
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh/>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
            v-hasPerm="['system:spotTicket-audit:audit']"
            type="success"
            :disabled="auditIds.length === 0"
            @click="handleAudit()"
        >
          <template #icon>
            <Plus/>
          </template>
          批量审核
        </el-button>
        <el-button
            v-hasPerm="['modules:spotTicket-audit:refund']"
            type="danger"
            :disabled="refundIds.length === 0"
            @click="handleRefund()"
        >
          <template #icon>
            <el-icon>
              <Close/>
            </el-icon>
          </template>
          批量退回
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column type="index" label="序号" width="80" align="center"/>
        <!--        <el-table-column-->
        <!--          key="deptId"-->
        <!--          label="旅行社Id"-->
        <!--          prop="deptId"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column
            key="deptName"
            label="旅行社名称"
            prop="deptName"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
        />
        <!--        <el-table-column-->
        <!--          key="categoryId"-->
        <!--          label="分类Id"-->
        <!--          prop="categoryId"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column
            key="categoryName"
            label="分类名称"
            prop="categoryName"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column key="num" label="预售数量" prop="num" min-width="100" align="center"/>
        <!--        <el-table-column-->
        <!--          key="recordBy"-->
        <!--          label="录入人Id"-->
        <!--          prop="recordBy"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column
            key="recordUserName"
            label="录入人"
            prop="recordUserName"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="recordTime"
            label="录入时间"
            prop="recordTime"
            min-width="180"
            align="center"
        />
        <!--        <el-table-column-->
        <!--          key="auditBy"-->
        <!--          label="审核人Id"-->
        <!--          prop="auditBy"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column
            key="auditUserName"
            label="审核人"
            prop="auditUserName"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="auditTime"
            label="审核时间"
            prop="auditTime"
            min-width="180"
            align="center"
        />
        <el-table-column label="审核结果" width="110" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.auditResult" code="auditResult"/>
          </template>
        </el-table-column>
        <el-table-column
            key="remark"
            label="审核意见"
            prop="remark"
            min-width="200"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template #default="scope">
            <el-button
                :disabled="scope.row.auditResult === 2"
                v-hasPerm="['system:spotTicket-audit:audit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Plus/>
              </template>
              审核
            </el-button>
            <el-button
                v-hasPerm="['system:spotTicket-audit:refund']"
                :disabled="scope.row.auditResult !== 2"
                type="danger"
                size="small"
                link
                @click="handleRefund(scope.row.id)"
            >
              <template #icon>
                <Close/>
              </template>
              退回
            </el-button>
            <el-button
                v-hasPerm="['system:spotTicket-audit:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialogDetails(scope.row.id)"
            >
              <template #icon>
                <Edit/>
              </template>
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="700px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="旅行社名称：" prop="deptName">
              {{ formData.deptName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称：" prop="categoryName">
              {{ formData.categoryName }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="预售数量：" prop="num">
              {{ formData.num }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="录入人：" prop="recordUserName">
              {{ formData.recordUserName }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="录入时间：" prop="recordTime">
              {{ formData.recordTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核状态：" prop="auditResult">
              <el-radio-group v-model="formData.auditResult">
                <el-radio :value="2">审核通过</el-radio>
                <el-radio :value="3">审核拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="审核意见：" prop="auditOpinion">
          <el-input
              v-model="formData.remark"
              type="textarea"
              placeholder="审核意见"
              maxlength="300"
              show-word-limit
              rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="loading" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预售票数据审核表单弹窗 -->
    <el-dialog
        v-model="dialogDetails.visible"
        :title="dialogDetails.title"
        width="700px"
        @close="handleCloseDialogDetails"
    >
      <el-form ref="dataFormRefDetails" :model="formData" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="旅行社名称：" prop="deptName">
              {{ formData.deptName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称：" prop="categoryName">
              {{ formData.categoryName }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="预售数量：" prop="num">
              {{ formData.num }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="录入人：" prop="recordUserName">
              {{ formData.recordUserName }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="录入时间：" prop="recordTime">
              {{ formData.recordTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核人：" prop="auditUserName">
              {{ formData.auditUserName }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="审核时间：" prop="auditTime">
              {{ formData.auditTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核结果：" prop="auditResult">
              <span v-if="formData.auditResult === 0">未审核</span>
              <span v-else-if="formData.auditResult === 1">待审核</span>
              <span v-else-if="formData.auditResult === 2">审核通过</span>
              <span v-else-if="formData.auditResult === 3">审核拒绝</span>
              <span v-else></span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="审核意见：" prop="remark">
            {{ formData.remark }}
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialogDetails()">返回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import DeptAPI from "@/api/system/dept";
import SpotTicketAuditAPI, {
  SpotTicketForm,
  SpotTicketPageQuery,
  SpotTicketPageVO,
} from "@/api/system/spot-ticket-audit";
import SpotCategoryAPI from "@/api/system/spot-category";

defineOptions({
  name: "SpotTicketAudit",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const dataFormRefDetails = ref(ElForm);
const deptOptions = ref<OptionType[]>();
const categoryOptions = ref<OptionType[]>();
const loading = ref(false);
const auditIds = ref<number[]>([]);
const refundIds = ref<number[]>([]);
const total = ref(0);


const now = new Date();
const startOfDay = new Date(now);
startOfDay.setHours(0, 0, 0, 0);

const endOfDay = new Date(now);
endOfDay.setHours(23, 59, 59, 999);

const format = (date: Date) => {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  const h = String(date.getHours()).padStart(2, '0');
  const mi = String(date.getMinutes()).padStart(2, '0');
  const s = String(date.getSeconds()).padStart(2, '0');
  return `${y}-${m}-${d} ${h}:${mi}:${s}`;
};

const queryParams = reactive<SpotTicketPageQuery>({
  pageNum: 1,
  pageSize: 10,
  auditResult: "1", // 设置默认值为 "待审核"
  //recordTime:[format(startOfDay), format(endOfDay)]
});

// 预售票数据审核表格数据
const pageData = ref<SpotTicketPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

const dialogDetails = reactive({
  title: "",
  visible: false,
});

// 预售票数据审核表单数据
const formData = reactive<SpotTicketForm>({});

// 预售票数据审核表单校验规则
const rules = reactive({
  auditResult: [{required: true, message: "请选择审核结果", trigger: "blur"}],
});

/** 查询预售票数据审核 */
function handleQuery() {
  loading.value = true;
  SpotTicketAuditAPI.getPage(queryParams)
      .then((data) => {
        pageData.value = data.list;
        total.value = data.total;
      })
      .finally(() => {
        loading.value = false;
      });
}

/** 重置预售票数据审核查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  auditIds.value = selection
      .filter((item: any) => item.auditResult === 1 || item.auditResult === 3)
      .map((item: any) => item.id);
  refundIds.value = selection
      .filter((item: any) => item.auditResult === 2)
      .map((item: any) => item.id);
}

/** 打开预售票数据审核弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "预售票数据审核";
    SpotTicketAuditAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增预售票数据审核";
  }
}

/** 打开预售票数据审核弹窗 */
function handleOpenDialogDetails(id?: number) {
  dialogDetails.visible = true;
  if (id) {
    dialogDetails.title = "预售票数据审核详情";
    SpotTicketAuditAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增预售票数据审核";
  }
}

/** 提交预售票数据审核表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        if (formData.auditResult < 2) {
          return ElMessage.error("请选择审核结果");
        }
        SpotTicketAuditAPI.update(id, formData)
            .then(() => {
              ElMessage.success("审核成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      } else {
        SpotTicketAuditAPI.add(formData)
            .then(() => {
              ElMessage.success("新增成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭预售票数据审核弹窗 */
function handleCloseDialogDetails() {
  dialogDetails.visible = false;
  dataFormRefDetails.value.resetFields();
  dataFormRefDetails.value.clearValidate();
  formData.id = undefined;
}

/** 关闭预售票数据审核弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

function handleRefund(id?: number) {
  const ids = [id || refundIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选退回项");
    return;
  }

  ElMessageBox.confirm("确认退回已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
      () => {
        loading.value = true;
        SpotTicketAuditAPI.refundByIds(ids)
            .then(() => {
              ElMessage.success("退回成功");
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      },
      () => {
        ElMessage.info("已取消退回");
      }
  );
}

/** 退回预售票数据审核 */
function handleAudit(id?: number) {
  const ids = [id || auditIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选审核项");
    return;
  }

  ElMessageBox.confirm("确认审核已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
      () => {
        loading.value = true;
        SpotTicketAuditAPI.auditByIds(ids)
            .then(() => {
              ElMessage.success("审核成功");
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      },
      () => {
        ElMessage.info("已取消审核");
      }
  );
}

if (onMounted) {
  onMounted(async () => {
    // 加载区域下拉数据源
    deptOptions.value = await DeptAPI.getOptions();
    // 加载分类下拉数据源
    categoryOptions.value = await SpotCategoryAPI.getOptions();
    handleQuery();
  });
}
</script>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left !important;
}

:deep(.el-popper) {
  max-width: 300px;
}
</style>
